$(function() {

    initArtcateList()
    let layer = layui.layer

    let form = layui.form

    function initArtcateList() {
        $.ajax({
            method: 'GET',
            url: '/my/article/cates',
            success: function(res) {
                var htmlstr = template('tpl-table', res)
                $('tbody').html(htmlstr)
            }
        })
    }

    let index = null

    $('#btnAddcate').on('click', function() {
        index = layer.open({
            title: '添加文章分类',
            type: 1,
            area: ['500px', '250px'],
            content: $('#dialog-add').html()
        });
    })

    $('body').on('submit', '#form-add', function(e) {
        e.preventDefault() //阻止默认
        $.ajax({
            method: 'POST',
            url: '/my/article/addcates',
            data: $(this).serialize(), //获取表单所有数据
            success: function(res) {
                if (res.status !== 0) return layer.msg('新增分类失败')
                initArtcateList()
                layer.msg('新增分类成功')
                layer.close(index)
            }
        })
    })

    // 点击编辑
    let id;
    $('body').on('click', '.btn-edit', function() {
        index = layer.open({
            title: '添加文章分类',
            type: 1,
            area: ['500px', '250px'],
            content: $('#dialog-edit').html()
        });

        //获取信息
        id = $(this).attr('data-id')
        $.ajax({
            method: 'GET',
            url: `/my/article/cates/${id}`,
            success: function(res) {
                form.val('form-edit', res.data)
            }
        })
    })

    //确认修改
    $('body').on('submit', '#form-edit', function(e) {
        e.preventDefault()
        $.ajax({
            method: 'POST',
            url: "/my/article/updatecate",
            data: $(this).serialize() + '&Id=' + id,
            success: function(res) {
                if (res.status !== 0) return layer.msg('修改文章失败')
                layer.msg('修改文章成功')
                layer.close(index)
                initArtcateList()
            }
        })
    })

    // 删除功能
    $('body').on('click', '.btn-delete', function() {
        let id = $(this).attr('data-Id')
        layer.confirm('确认删除?', { icon: 3, title: '提示' }, function(index) {
            $.ajax({
                method: 'GET',
                url: '/my/article/deletecate/' + id,
                success: function(res) {
                    if (res.status !== 0) return layer.msg('删除失败')
                    layer.msg('删除成功')
                    layer.close(index)
                    initArtcateList()
                }
            })
        });
    })
})